package cn.xiaopengstack.config;

import io.micrometer.observation.ObservationRegistry;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.DefaultChatClientBuilder;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.observation.ChatClientObservationConvention;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * @author jiangyangang
 */
@Configuration
public class AiClientConfig {

    @Bean
    public OpenAiApi openAiApi(SpringAiProperties properties) {
        return OpenAiApi.builder()
                .restClientBuilder(RestClient.builder().requestInterceptor(new RestClientFilter()))
                .webClientBuilder(WebClient.builder().filter(new AiModelCommunicationFilterFunction()))
                .baseUrl(properties.getOpenAi().getBaseUrl())
                .apiKey(properties.getOpenAi().getApiKey())
                .build();
    }

    /**
     * deepseek客户端
     * @param openAiApi
     * @return
     */
    @Bean("deepseekAiClient")
    public OpenAiChatModel deepSeekChatClient(OpenAiApi openAiApi){

        OpenAiChatModel openAiChatModel = OpenAiChatModel.builder()
                .openAiApi(openAiApi)
                .build();
        return openAiChatModel;
    }


    @Bean
    public ChatMemory chatMemory() {
        return new InMemoryChatMemory();
    }

    @Bean("deepseekChatClient")
    public ChatClient chatClient(@Qualifier("deepseekAiClient") OpenAiChatModel openAiChatModel,
                                 @Qualifier("syncMcpToolCallbackProvider") ToolCallbackProvider syncMcpToolCallbackProvider,
                                 ChatMemory chatMemory){
        DefaultChatClientBuilder defaultChatClientBuilder = new DefaultChatClientBuilder(openAiChatModel, ObservationRegistry.NOOP, (ChatClientObservationConvention) null);
        return defaultChatClientBuilder
                .defaultTools(syncMcpToolCallbackProvider)
                .defaultAdvisors(new PromptChatMemoryAdvisor(chatMemory))
                .defaultOptions(OpenAiChatOptions.builder()
                        .model("deepseek-chat")
                        .build())
                .build();
    }


}
